package com.fht.spring_boot_study.model.test.service.impl;

import com.fht.spring_boot_study.model.common.entity.ResultEntity;
import com.fht.spring_boot_study.model.common.entity.SearchBean;
import com.fht.spring_boot_study.model.test.dao.CityDao;
import com.fht.spring_boot_study.model.test.entity.City;
import com.fht.spring_boot_study.model.test.service.CityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDao cityDao;
    @Override
    @Transactional
    public ResultEntity<City> insertCity(City city) {
        cityDao.insertCity(city);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Insert Success",city);
    }

    @Override
    @Transactional
    public ResultEntity<City> updateCity(City city) {
        cityDao.updateCity(city);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Update Success",city);
    }

    @Override
    @Transactional
    public ResultEntity<Object> deleteCityByCityId(int cityId) {
        cityDao.deleteCityByCityId(cityId);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Delete Success");
    }

    @Override
    public City getCityByCityId(int cityId) {
       return cityDao.getCityByCityId(cityId);

    }

    @Override
    public List<City> getCitiesByCountryId(int countryId) {
        return Optional.ofNullable(cityDao.getCitiesByCountryId(countryId)).orElse(Collections.emptyList());
    }

    @Override
    public PageInfo<City> getCitiesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(),searchBean.getPageSize());
        return new PageInfo<City>(
                Optional.ofNullable(cityDao.getCitiesBySearchBean(searchBean))
                .orElse(Collections.emptyList()));
    }
}
